#include "Thread.hpp"
#include "Lock.hpp"
#include <unistd.h>

using namespace std;

void fun1(void *args)
{
    int cnt = 5;
    while (cnt--)
    {
        cout << "#########################" << endl;
        sleep(1);
    }
}
void showstatue(int n)
{
    if (n == 0)
        cout << "NEW" << endl;
    else if (n == 1)
        cout << "RUNNING" << endl;
    else
        cout << "EXIT" << endl;
}

int tickets = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void threadRoutine(void *args)
{
    std::string message = static_cast<const char *>(args);
    while (true)
    {
        {
            LockGuard lock(&mutex); // 自动化加锁和解锁
            if (tickets > 0)        // tickets == 1; a, b, c,d
            {
                // a,b,c,d
                usleep(1000);
                cout << message << " get a ticket: " << tickets-- << endl;
            }
            else
            {
                break;
            }
        }
    }

    return;
}

int main()
{
    // 封装线程库的测试代码
    //  Thread td1(1, fun1, (void*)"holle");
    //  cout << td1.name() << " : " << td1.thread_id() << " : "; showstatue(td1.statue());
    //  td1.run();
    //  cout << td1.name() << " : " << td1.thread_id() << " : "; showstatue(td1.statue());
    //  td1.join();
    //  cout << td1.name() << " : " << td1.thread_id() << " : "; showstatue(td1.statue());

    // 封装锁的测试代码
    Thread t1(1, threadRoutine, (void *)"hellobit1");
    Thread t2(2, threadRoutine, (void *)"hellobit2");
    Thread t3(3, threadRoutine, (void *)"hellobit3");

    t1.run();
    t2.run();
    t3.run();

    t1.join();
    t2.join();
    t3.join();

    return 0;
}